package com.ruoyi.merchant.service.impl;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.merchant.domain.MerchantRegionBinding;
import com.ruoyi.merchant.domain.dto.MerchantRegionBindingDTO;
import com.ruoyi.merchant.domain.vo.MerchantRegionBindingVO;
import com.ruoyi.merchant.mapper.MerchantRegionBindingMapper;
import com.ruoyi.merchant.service.IMerchantRegionBindingService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;

/**
 * 商家区域绑定Service业务层处理
 * 
 * @author xperia
 */
@Service
public class MerchantRegionBindingServiceImpl implements IMerchantRegionBindingService {
    
    @Autowired
    private MerchantRegionBindingMapper merchantRegionBindingMapper;

    /**
     * 查询商家的区域绑定列表
     */
    @Override
    public List<MerchantRegionBindingVO> selectBindingList() {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        List<MerchantRegionBinding> bindings = merchantRegionBindingMapper.selectBindingsByMerchantId(merchantId);
        
        return bindings.stream().map(binding -> {
            MerchantRegionBindingVO vo = new MerchantRegionBindingVO();
            BeanUtils.copyProperties(binding, vo);
            vo.setCreatedAt(binding.getCreateTime());
            vo.setUpdatedAt(binding.getUpdateTime());

            vo.setRegionName(String.valueOf(binding.getRegionId()));
            
            vo.setStatusName(getStatusName(binding.getStatus()));
            
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 查询区域绑定详情
     */
    @Override
    public MerchantRegionBindingVO selectBindingById(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        MerchantRegionBinding binding = merchantRegionBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("区域绑定不存在或无权访问");
        }
        
        MerchantRegionBindingVO vo = new MerchantRegionBindingVO();
        BeanUtils.copyProperties(binding, vo);
        vo.setCreatedAt(binding.getCreateTime());
        vo.setUpdatedAt(binding.getUpdateTime());

        vo.setRegionName(String.valueOf(binding.getRegionId()));
        
        vo.setStatusName(getStatusName(binding.getStatus()));
        
        return vo;
    }

    /**
     * 新增区域绑定
     */
    @Override
    @Transactional
    public int insertBinding(MerchantRegionBindingDTO dto) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 检查是否已绑定（未删除的记录）
        if (merchantRegionBindingMapper.checkBindingExists(merchantId, dto.getRegionId(), null) > 0) {
            throw new ServiceException("该区域已绑定，请勿重复绑定");
        }

        // 检查是否存在已删除的记录
        MerchantRegionBinding deletedBinding =
                merchantRegionBindingMapper.selectDeletedBinding(merchantId, dto.getRegionId());

        if (deletedBinding != null) {
            // 存在已删除记录 → 恢复记录
            deletedBinding.setServiceRadius(dto.getServiceRadius());
            deletedBinding.setStatus(0);
            return merchantRegionBindingMapper.restoreBinding(deletedBinding);
        } else {
            // 不存在已删除记录 → 新增记录
            MerchantRegionBinding binding = new MerchantRegionBinding();
            BeanUtils.copyProperties(dto, binding);
            binding.setMerchantId(merchantId);
            binding.setStatus(0);
            return merchantRegionBindingMapper.insertBinding(binding);
        }
    }


    /**
     * 修改区域绑定
     */
    @Override
    @Transactional
    public int updateBinding(MerchantRegionBindingDTO dto) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        if (dto.getBindingId() == null) {
            throw new ServiceException("绑定ID不能为空");
        }
        
        // 查询原绑定信息
        MerchantRegionBinding existBinding = merchantRegionBindingMapper.selectBindingById(
            dto.getBindingId(), merchantId);
        if (existBinding == null) {
            throw new ServiceException("区域绑定不存在或无权访问");
        }
        
        // 如果修改了区域ID，检查是否已绑定
        if (!existBinding.getRegionId().equals(dto.getRegionId())) {
            if (merchantRegionBindingMapper.checkBindingExists(merchantId, dto.getRegionId(), dto.getBindingId()) > 0) {
                throw new ServiceException("该区域已绑定，请勿重复绑定");
            }
        }
        
        MerchantRegionBinding binding = new MerchantRegionBinding();
        BeanUtils.copyProperties(dto, binding);
        binding.setMerchantId(merchantId);
        
        return merchantRegionBindingMapper.updateBinding(binding);
    }

    /**
     * 启用区域绑定
     */
    @Override
    @Transactional
    public int enableBinding(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询绑定信息
        MerchantRegionBinding binding = merchantRegionBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("区域绑定不存在或无权访问");
        }
        
        return merchantRegionBindingMapper.updateBindingStatus(bindingId, merchantId, 0);
    }

    /**
     * 禁用区域绑定
     */
    @Override
    @Transactional
    public int disableBinding(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询绑定信息
        MerchantRegionBinding binding = merchantRegionBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("区域绑定不存在或无权访问");
        }
        
        return merchantRegionBindingMapper.updateBindingStatus(bindingId, merchantId, 1);
    }

    /**
     * 删除区域绑定
     */
    @Override
    @Transactional
    public int deleteBinding(Long bindingId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询绑定信息
        MerchantRegionBinding binding = merchantRegionBindingMapper.selectBindingById(bindingId, merchantId);
        if (binding == null) {
            throw new ServiceException("区域绑定不存在或无权访问");
        }
        
        return merchantRegionBindingMapper.deleteBinding(bindingId, merchantId);
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        switch (status) {
            case 0: return "有效";
            case 1: return "禁用";
            default: return "未知";
        }
    }
}

